// +----------------------------------------------------------------------
// | Static Plugin for ThinkAdmin
// +----------------------------------------------------------------------
// | 官方网站: https://thinkadmin.top
// +----------------------------------------------------------------------
// | 版权所有 2014~2025 ThinkAdmin [ thinkadmin.top ]
// +----------------------------------------------------------------------
// | 开源协议 ( https://mit-license.org )
// | 免责声明 ( https://thinkadmin.top/disclaimer )
// +----------------------------------------------------------------------
// | gitee 代码仓库：https://gitee.com/zoujingli/think-plugs-static
// | github 代码仓库：https://github.com/zoujingli/think-plugs-static
// +----------------------------------------------------------------------
// | 自定义后台扩展脚本，需要在加载 admin.js 后载入
// | 使用 composer require zoujingli/think-plugs-static 时不会更新此文件
// +----------------------------------------------------------------------

$(function () {
    window.$body = $('body');

    /*! 注册单次事件 */
    function onEvent(event, select, callable) {
        return $body.off(event, select).on(event, select, callable);
    }
    /*! 注册 data-print 页面打印 事件行为 */
    onEvent('click', '[data-print]', function () {
         // 需要打印的内容
        window.document.body.innerHTML = document.querySelector('.print_content').innerHTML;
        window.print();
        window.location.reload(); // 打印完成后重新加载页面
    });
    //QQ地图
    onEvent('click', '[data-map]', function () {
        this.id = this.dataset.id = this.id || (function (date) {
            return (date + Math.random()).replace('0.', '');
        })(layui.util.toDateString(Date.now(), 'yyyyMMddHHmmss-'));
        let location = tapiRoot + '/api.map/qqmap';
        $.form.modal(location, this.dataset, '地图选点');
    });
    
    /**
     * 高德地图
     * <label class="layui-form-item relative block">
     *     <span class="help-label"><b>坐标-纬度</b></span>
     *         <span class="flex flex-align-center">
     *            <input type="text" name="lat" value='{$vo.lat|default=""}'  placeholder="请输入纬度" required class="layui-input">
     *            <button type="button" data-amap data-address="[name=address]"  data-lat="[name=lat]" data-lng="[name=lng]"  class="margin-left-10  layui-btn layui-btn-sm">
     *                <i class="layui-icon layui-icon-location"></i>地图选点
     *             </button>
     *      </span>
     * </label>
     */
    onEvent('click', '[data-amap]', function () {
        this.id = this.dataset.id = this.id || (function (date) {
            return (date + Math.random()).replace('0.', '');
        })(layui.util.toDateString(Date.now(), 'yyyyMMddHHmmss-'));
        let location = tapiRoot + '/api.map/amap';
        $.form.modal(location, this.dataset, '地图选点');
    });



    $body.on('reInit', function (evt, $dom) {
        $($dom).find('[required]').map(function () {//必选*
            this.$parent = $(this).parents('.layui-form-item');
            this.$parent.addClass('label-required-prev');
        })
        //年选择器
        $($dom).find('[data-year-input]').each(function () {
            this.setAttribute('autocomplete', 'off')
            const that = $(this);
            laydate.render({
                type: 'year',
                elem: this,
                done: function (value) {
                    $(this.elem).val(value).trigger('change');
                },
            });
        })
        $($dom).off('click', '[data-close]').on('click', '[data-close]', function () {
            $.base.onConfirm(this.dataset.confirm, () => layer.close());
        })
        //时间选择器
        $($dom).find('[data-time]').each(function () {
            this.setAttribute('autocomplete', 'off')
            const that = $(this);
            laydate.render({
                type: 'time',
                elem: this,
                done: function (value) {
                    $(this.elem).val(value).trigger('change');
                },
            });
        })

        //日期+时间选择器
        $($dom).find('input[data-date-time-range]').map(function () {
            this.setAttribute('autocomplete', 'off');
            laydate.render({
                type: this.getAttribute('data-date-input') || 'datetime',
                fullPanel: true,
                range: true,
                elem: this,
                done: function (value) {
                    $(this.elem).val(value).trigger('change');
                }
            });
        });
        //图片不变形预览
        //<div data-image="https://xxx.png"></div>
        $($dom).find('[data-image]').map(function () {
            this.setAttribute('autocomplete', 'off');
            let img = new Image();
            let imageUrl = $(this).attr('data-image');
            const that=this;
            img.src = imageUrl; // 尝试加载图片
            img.onerror = function() {//URL验证
                this.onerror = null; // 防止无限循环
                imageUrl=baseRoot + 'theme/img/404_icon.png';
                //this.src = imageUrl; // 设置默认图片
                $(that).css({
                    'background': 'url(' + imageUrl + ') no-repeat center',
                    'background-size': 'cover',
                    'height': '75px',
                    'width': '75px',
                });
                $(that).attr('data-tips-image',imageUrl);
            };
            img.onload = function() {
                // 图片加载成功，设置背景
                $(that).css({
                    'background': 'url(' + imageUrl + ') no-repeat center',
                    'background-size': 'cover',
                    'height': '75px',
                    'width': '75px',
                });
                $(that).attr('data-tips-image',imageUrl);
            };
        });
    });



    /*! 追加 require 配置参数
    /*! 加载的文件不能与主配置重复 */
    require.config({
        paths: {
            'amap': ['https://webapi.amap.com/maps?v=2.0&key=API_KEY'],
            'qqmap': ['https://map.qq.com/api/gljs?v=1.exp&key=API_KEY'],
            // 'vue': ['plugs/vue/vue.min'],
        },
        shim: {
            // 'amap': {deps: ['css!' + baseRoot + 'extra/amap.css']},
            // 'vue': ['json']
        },
    });
    // // 基于 Require 加载测试
    // require(['vue', 'md5'], function (vue, md5) {
    //     console.log(vue)
    //     console.log(md5.hash('content'))
    // });

    /*! 其他 javascript 脚本代码 */

    // 显示表格图片
    window.showTableImage = function (image, circle, size, title) {
        return $.layTable.showImage(image, circle, size, title);
    };

    // 显示商品规格
    window.showSpec = function (spec) {
        let names = [];
        return layui.each(spec.split(';;'), function (i, vv) {
            names.push(vv.split('::').pop());
        }), names.join(' ');
    }

    /*! 上传可排序的多张图片
    * <div class="layui-form-item margin-bottom-5">
    *    <label class="help-label"><b>可排序多图上传</b></label>
    *    <div class="layui-textarea help-images">
    *        <input type="hidden" value="" name="sortable_images">
    *    </div>
    *    <script>
    *        $('[name=sortable_images]').uploadSortableImages();
    *   </script>
    </div>
    */
    $.fn.uploadSortableImages = function () {
        return this.each(function () {
            if (this.dataset.inited) return; else this.dataset.inited = 'true';
            let $bt = $('<div class="uploadimage"><span><a data-file="mul" class="layui-icon layui-icon-upload-drag"></a></span><span data-file="images"></span></div>');
            let ims = this.value ? this.value.split('|') : [], $in = $(this).after($bt);
            $bt.find('[data-file]').attr({
                'data-path': $in.data('path') || '', 'data-size': $in.data('size') || 0, 'data-type': $in.data('type') || 'gif,png,jpg,jpeg',
                'data-max-width': $in.data('max-width') || 0, 'data-max-height': $in.data('max-height') || 0,
                'data-cut-width': $in.data('cut-width') || 0, 'data-cut-height': $in.data('cut-height') || 0,
            }).on('push', function (evt, src) {
                ims.push(src), $in.val(ims.join('|')).trigger('change'), showImageContainer([src]);
            }) && (ims.length > 0 && showImageContainer(ims));

            function showImageContainer(srcs) {
                $(srcs).each(function (idx, src, $img) {
                    $img = $('<div class="uploadimage uploadimagemtl" draggable="true"><div><a class="layui-icon">&#xe603;</a><a class="layui-icon">&#x1006;</a><a class="layui-icon">&#xe602;</a></div></div>');
                    $img.attr('data-tips-image', encodeURI(src)).css('backgroundImage', 'url(' + encodeURI(src) + ')').on('click', 'a', function (event, index, prevs, $item) {
                        event.stopPropagation(), $item = $(this).parent().parent(), index = $(this).index();
                        if (index === 2 && $item.index() !== $bt.prevAll('div.uploadimage').length) $item.next().after($item);
                        else if (index === 0 && $item.index() > 1) $item.prev().before($item); else if (index === 1) $item.remove();
                        updateImageOrder();
                    }), $bt.before($img);
                });
            }

            // 更新图片顺序
            function updateImageOrder() {
                ims = [];
                // 按照DOM顺序收集图片URL（从前到后）
                $bt.prevAll('.uploadimagemtl').each(function() {
                    let url = $(this).attr('data-tips-image');
                    if (url) {
                        ims.unshift(decodeURI(url)); // 使用unshift因为prevAll是反向的
                    }
                });
                $in.val(ims.join('|')).trigger('change');
            }

            // 创建冒泡特效
            function createBubbleEffect(x, y) {
                // 创建多个泡泡以增强效果
                for (let i = 0; i < 3; i++) {
                    let $bubble = $('<div class="bubble-effect"></div>');
                    let size = 4 + Math.random() * 4;
                    let offsetX = (Math.random() - 0.5) * 20;
                    let offsetY = (Math.random() - 0.5) * 20;
                    
                    $bubble.css({
                        position: 'fixed',
                        left: x + offsetX,
                        top: y + offsetY,
                        width: size + 'px',
                        height: size + 'px',
                        backgroundColor: 'rgba(30, 159, 255, ' + (0.6 + Math.random() * 0.4) + ')',
                        borderRadius: '50%',
                        pointerEvents: 'none',
                        zIndex: 9999,
                        boxShadow: '0 0 ' + (4 + Math.random() * 4) + 'px rgba(30, 159, 255, 0.8)'
                    });
                    
                    $('body').append($bubble);
                    
                    // 添加动画效果
                    $bubble.animate({
                        top: y - 30 - Math.random() * 40,
                        left: x + offsetX + (Math.random() - 0.5) * 50,
                        opacity: 0,
                        width: (size * 2) + 'px',
                        height: (size * 2) + 'px'
                    }, 600 + Math.random() * 400, function() {
                        $bubble.remove();
                    });
                }
            }

            // 使用自定义拖拽实现替换HTML5拖拽
            let dragSrcEl = null;
            let isDragging = false;
            let lastTarget = null;
            let lastInsertTime = 0;
            
            $bt.parent().on('mousedown', '.uploadimagemtl', function(e) {
                // 只有在图片上按下鼠标才开始拖拽（避免在操作按钮上触发）
                if (!$(e.target).is('a')) {
                    dragSrcEl = $(this);
                    isDragging = true;
                    dragSrcEl.addClass('dragging');
                    lastTarget = null;
                    lastInsertTime = 0;
                    e.preventDefault();
                    
                    // 禁用文本选择
                    $('body').addClass('no-select');
                }
            });

            $(document).on('mousemove', function(e) {
                if (isDragging && dragSrcEl) {
                    e.preventDefault();
                    
                    // 添加冒泡特效，控制频率避免过多特效
                    if (Math.random() > 0.9) {
                        createBubbleEffect(e.clientX, e.clientY);
                    }
                }
            });

            $bt.parent().on('mousemove', '.uploadimagemtl', function(e) {
                if (isDragging && dragSrcEl && dragSrcEl[0] !== this) {
                    // 限制交换频率，避免过于频繁的交换
                    let now = Date.now();
                    if (lastTarget === this && (now - lastInsertTime) < 100) {
                        return;
                    }
                    
                    lastTarget = this;
                    lastInsertTime = now;
                    
                    // 计算鼠标相对于当前元素的位置
                    let rect = this.getBoundingClientRect();
                    let midX = rect.left + rect.width / 2;
                    
                    // 根据鼠标位置决定是插入到前面还是后面
                    if (e.clientX < midX) {
                        $(this).before(dragSrcEl);
                    } else {
                        $(this).after(dragSrcEl);
                    }
                }
            });

            function stopDragging() {
                if (isDragging && dragSrcEl) {
                    dragSrcEl.removeClass('dragging');
                    dragSrcEl = null;
                    isDragging = false;
                    lastTarget = null;
                    updateImageOrder();
                    
                    // 恢复文本选择
                    $('body').removeClass('no-select');
                }
            }

            $(document).on('mouseup', function() {
                stopDragging();
            });
        });
    };
});